<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登陆注册 - spot.gitagent.io</title>
    <!-- Supabase客户端 -->
    <script src="./supabase-client.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
            z-index: 10070;
        }

        .auth-container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
            width: 100%;
            max-width: 400px;
            margin: 20px;
        }

        .auth-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .auth-header h1 {
            font-size: 28px;
            margin-bottom: 10px;
            font-weight: 700;
        }

        .auth-header p {
            opacity: 0.9;
            font-size: 16px;
        }

        .auth-header h2 {
            font-size: 20px;
            margin-top: 10px;
            font-weight: 600;
            opacity: 0.95;
        }

        .auth-tabs {
            display: flex;
            background: #f8f9fa;
        }

        .tab-button {
            flex: 1;
            padding: 15px;
            border: none;
            background: transparent;
            cursor: pointer;
            font-size: 16px;
            font-weight: 600;
            color: #666;
            transition: all 0.3s ease;
        }

        .tab-button.active {
            background: white;
            color: #667eea;
            border-bottom: 3px solid #667eea;
        }

        .auth-content {
            padding: 30px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
        }

        .form-group input {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e1e5e9;
            border-radius: 10px;
            font-size: 16px;
            transition: border-color 0.3s ease;
        }

        .form-group input:focus {
            outline: none;
            border-color: #667eea;
        }

        .auth-button {
            width: 100%;
            padding: 15px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s ease;
        }

        .auth-button:hover {
            transform: translateY(-2px);
        }

        .auth-button:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .auth-footer {
            text-align: center;
            padding: 20px 30px;
            background: #f8f9fa;
            color: #666;
        }

        .auth-footer a {
            color: #667eea;
            text-decoration: none;
            font-weight: 600;
        }

        .error-message {
            background: #fee;
            color: #c33;
            padding: 10px;
            border-radius: 8px;
            margin-bottom: 20px;
            border: 1px solid #fcc;
        }

        .success-message {
            background: #efe;
            color: #3c3;
            padding: 10px;
            border-radius: 8px;
            margin-bottom: 20px;
            border: 1px solid #cfc;
        }

        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .hidden {
            display: none;
        }

        /* 邮件验证模态框样式 */
        .email-verification-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.7);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }
        
        .email-verification-modal.hidden {
            display: none;
        }

        .verification-content {
            background: white;
            padding: 40px 30px;
            border-radius: 16px;
            text-align: center;
            max-width: 450px;
            width: 90%;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
            animation: modalSlideIn 0.3s ease-out;
            position: relative;
        }
        
        .verification-close-x {
            position: absolute;
            top: 15px;
            right: 15px;
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: #666;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            transition: all 0.2s ease;
        }
        
        .verification-close-x:hover {
            background: #f0f0f0;
            color: #333;
        }

        @keyframes modalSlideIn {
            from {
                opacity: 0;
                transform: translateY(-20px) scale(0.95);
            }
            to {
                opacity: 1;
                transform: translateY(0) scale(1);
            }
        }

        /* 验证码表单样式 */
        .verification-header {
            text-align: center;
            margin-bottom: 30px;
        }

        .verification-header .verification-icon {
            font-size: 48px;
            margin-bottom: 15px;
        }

        .verification-header h3 {
            color: #333;
            margin: 0 0 10px 0;
            font-size: 24px;
        }

        .verification-header p {
            color: #666;
            margin: 0 0 15px 0;
            line-height: 1.5;
        }

        .verification-email-display {
            background: #f8f9fa;
            padding: 10px 15px;
            border-radius: 8px;
            color: #4CAF50;
            font-weight: 500;
            margin: 10px 0;
        }

        .verification-timer {
            text-align: center;
            color: #666;
            font-size: 14px;
            margin: 15px 0;
        }

        #timer-countdown {
            color: #ff6b6b;
            font-weight: 500;
        }

        .verification-actions {
            margin-top: 20px;
            text-align: center;
        }

        .resend-button, .back-button {
            background: none;
            border: none;
            color: #667eea;
            cursor: pointer;
            text-decoration: underline;
            font-size: 14px;
            margin: 0 10px;
            padding: 5px 10px;
            transition: color 0.2s ease;
        }

        .resend-button:hover, .back-button:hover {
            color: #5a67d8;
        }

        .resend-button:disabled {
            color: #ccc;
            cursor: not-allowed;
            text-decoration: none;
        }

        .verification-icon {
            font-size: 48px;
            margin-bottom: 20px;
            display: block;
        }

        .verification-content h3 {
            color: #2d3748;
            margin-bottom: 15px;
            font-size: 24px;
            font-weight: 600;
        }

        .verification-content p {
            color: #4a5568;
            margin-bottom: 20px;
            line-height: 1.6;
            font-size: 16px;
        }

        .verification-email {
            background: #f7fafc;
            padding: 12px 16px;
            border-radius: 8px;
            margin: 20px 0;
            font-family: monospace;
            color: #2d3748;
            font-weight: 500;
            border: 2px solid #e2e8f0;
        }

        .verification-actions {
            display: flex;
            gap: 12px;
            margin-top: 25px;
            justify-content: center;
        }

        .verification-button {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
            min-width: 100px;
        }

        .verification-button.primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .verification-button.primary:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }

        .verification-button.secondary {
            background: #f7fafc;
            color: #4a5568;
            border: 2px solid #e2e8f0;
        }

        .verification-button.secondary:hover {
            background: #edf2f7;
            border-color: #cbd5e0;
        }

    </style>
</head>
<body>
    <div class="auth-container">
        <div class="auth-header">
            <h1 id="auth-title">登陆注册</h1>
        </div>


        <div class="auth-tabs">
            <button class="tab-button" onclick="switchTab('login')" id="login-tab">登录</button>
            <button class="tab-button active" onclick="switchTab('register')" id="register-tab">注册</button>
            <button class="tab-button" onclick="switchTab('forgot')" id="forgot-tab">找回密码</button>
        </div>

        <div class="auth-content">
            <div id="error-message" class="error-message hidden"></div>
            <div id="success-message" class="success-message hidden"></div>
            
            <!-- 邮件验证提醒模态框 -->
            <div id="email-verification-modal" class="email-verification-modal hidden" onclick="closeVerificationModalOnBackdrop(event)">
                <div class="verification-content" onclick="event.stopPropagation()">
                    <button class="verification-close-x" onclick="closeVerificationModal()" title="关闭">×</button>
                    <div class="verification-icon">📧</div>
                    <h3 id="verification-title">注册成功！</h3>
                    <p id="verification-message">我们已向您的邮箱发送了验证链接，请在24小时内完成验证。</p>
                    <div class="verification-email" id="verification-email-display"></div>
                    <div class="verification-actions">
                        <button class="verification-button primary" onclick="closeVerificationModal()" id="verification-close-btn">我知道了</button>
                        <button class="verification-button secondary" onclick="resendVerificationEmail()" id="verification-resend-btn">重新发送</button>
                    </div>
                </div>
            </div>

            <!-- 登录表单 -->
            <form id="login-form" class="auth-form hidden">
                <div class="form-group">
                    <label for="login-email" id="login-email-label">邮箱地址</label>
                    <input type="email" id="login-email" name="email" required>
                </div>
                <div class="form-group">
                    <label for="login-password" id="login-password-label">密码</label>
                    <input type="password" id="login-password" name="password" required>
                </div>
                <button type="submit" class="auth-button" id="login-button">
                    <span id="login-text">登录</span>
                    <div class="loading hidden" id="login-loading"></div>
                </button>
                <div style="margin-top: 15px; text-align: center;">
                    <button type="button" onclick="switchTab('forgot')" style="background: none; border: none; color: #667eea; cursor: pointer; text-decoration: underline; font-size: 14px;">
                        <span id="forgot-password-link">忘记密码？</span>
                    </button>
                </div>
            </form>

            <!-- 注册表单 -->
            <form id="register-form" class="auth-form">
                <div class="form-group">
                    <label for="register-username" id="register-username-label">用户名</label>
                    <input type="text" id="register-username" name="username" required>
                </div>
                <div class="form-group">
                    <label for="register-email" id="register-email-label">邮箱地址</label>
                    <input type="email" id="register-email" name="email" required>
                </div>
                <div class="form-group">
                    <label for="register-password" id="register-password-label">密码</label>
                    <input type="password" id="register-password" name="password" required>
                </div>
                <div class="form-group">
                    <label for="register-confirm-password" id="register-confirm-password-label">确认密码</label>
                    <input type="password" id="register-confirm-password" name="confirm_password" required>
                </div>
                <button type="submit" class="auth-button" id="register-button">
                    <span id="register-text">注册</span>
                    <div class="loading hidden" id="register-loading"></div>
                </button>
            </form>

            <!-- 邮箱验证码表单 -->
            <form id="verification-form" class="auth-form hidden">
                <div class="verification-header">
                    <div class="verification-icon">📧</div>
                    <h3 id="verification-title">邮箱验证</h3>
                    <p id="verification-description">我们已向您的邮箱发送了6位数字验证码，请在下方输入验证码完成注册。</p>
                    <div class="verification-email-display" id="verification-email-display"></div>
                </div>
                <div class="form-group">
                    <label for="verification-code" id="verification-code-label">验证码</label>
                    <input type="text" id="verification-code" name="verification_code" maxlength="6" pattern="[0-9]{6}" required placeholder="请输入6位数字验证码" style="text-align: center; font-size: 18px; letter-spacing: 3px;">
                </div>
                <div class="verification-timer" id="verification-timer">
                    验证码将在 <span id="timer-countdown">10:00</span> 后过期
                </div>
                <button type="submit" class="auth-button" id="verification-button">
                    <span id="verification-text">验证并完成注册</span>
                    <div class="loading hidden" id="verification-loading"></div>
                </button>
                <div class="verification-actions">
                    <button type="button" class="resend-button" id="resend-code-button" onclick="resendVerificationCode()">
                        <span id="resend-text">重新发送验证码</span>
                    </button>
                    <button type="button" class="back-button" onclick="backToRegister()">
                        <span id="back-to-register">返回注册</span>
                    </button>
                </div>
            </form>

            <!-- 找回密码表单 -->
            <form id="forgot-form" class="auth-form hidden">
                <div class="form-group">
                    <label for="forgot-email" id="forgot-email-label">邮箱地址</label>
                    <input type="email" id="forgot-email" name="email" required placeholder="请输入您注册时使用的邮箱">
                </div>
                <p id="forgot-description" style="color: #666; font-size: 14px; margin-bottom: 20px; line-height: 1.5;">
                    请输入您注册时使用的邮箱地址，我们将向您发送密码重置链接。
                </p>
                <button type="submit" class="auth-button" id="forgot-button">
                    <span id="forgot-text">发送重置链接</span>
                    <div class="loading hidden" id="forgot-loading"></div>
                </button>
                <div style="margin-top: 15px; text-align: center;">
                    <button type="button" onclick="switchTab('login')" style="background: none; border: none; color: #667eea; cursor: pointer; text-decoration: underline;">
                        <span id="back-to-login">返回登录</span>
                    </button>
                </div>
            </form>
        </div>

        <div class="auth-footer">
            <a href="#" onclick="closeModal()" id="close-modal-link">关闭</a>
        </div>
    </div>

    <script src="i18n/index.js"></script>
    <script>
        // 多语言支持
        const translations = {
            zh: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                authTitle: "登陆注册",
                login: "登录",
                register: "注册",
                forgotPassword: "找回密码",
                emailLabel: "邮箱地址",
                passwordLabel: "密码",
                confirmPasswordLabel: "确认密码",
                usernameLabel: "用户名",
                emailPlaceholder: "邮箱地址",
                passwordPlaceholder: "密码",
                confirmPasswordPlaceholder: "确认密码",
                usernamePlaceholder: "用户名",
                welcomeBack: "欢迎回来",
                joinUs: "加入我们",
                close: "关闭",
                loginSuccess: "登录成功！",
                registerSuccess: "注册成功！",
                emailVerificationRequired: "注册成功！请检查您的邮箱并点击验证链接以激活账户。",
                emailVerificationNote: "我们已向您的邮箱发送了验证链接，请在24小时内完成验证。",
                emailVerificationClose: "我知道了",
                resendVerification: "重新发送",
                loginFailed: "登录失败，请重试",
                registerFailed: "注册失败",
                passwordMismatch: "两次输入的密码不一致",
                emailAlreadyRegistered: "该邮箱已注册，请直接登录",
                invalidCredentials: "邮箱或密码错误，请检查后重试",
                databaseError: "该邮箱可能已经注册，请尝试直接登录或使用其他邮箱",
                serviceUnavailable: "注册服务暂时不可用，请稍后再试",
                forgotEmailLabel: "邮箱地址",
                forgotDescription: "请输入您注册时使用的邮箱地址，我们将向您发送密码重置链接。",
                sendResetLink: "发送重置链接",
                backToLogin: "返回登录",
                resetEmailSent: "密码重置邮件已发送！请检查您的邮箱。",
                resetEmailFailed: "发送重置邮件失败，请重试",
                emailNotFound: "该邮箱未注册，请检查邮箱地址或先注册账户",
                forgotPasswordLink: "忘记密码？"
            },
            en: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                authTitle: "Login & Register",
                login: "Login",
                register: "Register",
                forgotPassword: "Forgot Password",
                emailLabel: "Email Address",
                passwordLabel: "Password",
                confirmPasswordLabel: "Confirm Password",
                usernameLabel: "Username",
                emailPlaceholder: "Email Address",
                passwordPlaceholder: "Password",
                confirmPasswordPlaceholder: "Confirm Password",
                usernamePlaceholder: "Username",
                welcomeBack: "Welcome Back",
                joinUs: "Join Us",
                close: "Close",
                loginSuccess: "Login successful!",
                registerSuccess: "Registration successful!",
                emailVerificationRequired: "Registration successful! Please check your email and click the verification link to activate your account.",
                emailVerificationNote: "We have sent a verification link to your email. Please complete verification within 24 hours.",
                emailVerificationClose: "Got it",
                resendVerification: "Resend",
                loginFailed: "Login failed, please try again",
                registerFailed: "Registration failed",
                passwordMismatch: "Passwords do not match",
                emailAlreadyRegistered: "Email already registered, please sign in directly",
                databaseError: "This email may already be registered. Please try logging in or use a different email",
                serviceUnavailable: "Registration service is temporarily unavailable. Please try again later",
                invalidCredentials: "Invalid email or password, please check and try again",
                forgotEmailLabel: "Email Address",
                forgotDescription: "Enter the email address you used to register, and we'll send you a password reset link.",
                sendResetLink: "Send Reset Link",
                backToLogin: "Back to Login",
                resetEmailSent: "Password reset email sent! Please check your inbox.",
                resetEmailFailed: "Failed to send reset email, please try again",
                emailNotFound: "This email is not registered. Please check the email address or register first",
                forgotPasswordLink: "Forgot Password?"
            },
            es: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                authTitle: "Iniciar Sesión y Registrarse",
                login: "Iniciar Sesión",
                register: "Registrarse",
                emailPlaceholder: "Dirección de Email",
                passwordPlaceholder: "Contraseña",
                confirmPasswordPlaceholder: "Confirmar Contraseña",
                usernamePlaceholder: "Nombre de Usuario",
                welcomeBack: "Bienvenido de Vuelta",
                joinUs: "Únete a Nosotros",
                backToHome: "Volver al Inicio",
                loginSuccess: "¡Inicio de sesión exitoso!",
                registerSuccess: "¡Registro exitoso!",
                loginFailed: "Error al iniciar sesión, inténtalo de nuevo",
                registerFailed: "Error en el registro",
                passwordMismatch: "Las contraseñas no coinciden",
                emailAlreadyRegistered: "El email ya está registrado, inicia sesión directamente",
                invalidCredentials: "Email o contraseña inválidos, verifica e inténtalo de nuevo"
            },
            fr: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                authTitle: "Connexion et Inscription",
                login: "Connexion",
                register: "Inscription",
                emailPlaceholder: "Adresse Email",
                passwordPlaceholder: "Mot de Passe",
                confirmPasswordPlaceholder: "Confirmer le Mot de Passe",
                usernamePlaceholder: "Nom d'Utilisateur",
                welcomeBack: "Bon Retour",
                joinUs: "Rejoignez-Nous",
                backToHome: "Retour à l'Accueil",
                loginSuccess: "Connexion réussie !",
                registerSuccess: "Inscription réussie !",
                loginFailed: "Échec de la connexion, réessayez",
                registerFailed: "Échec de l'inscription",
                passwordMismatch: "Les mots de passe ne correspondent pas",
                emailAlreadyRegistered: "L'email est déjà enregistré, connectez-vous directement",
                invalidCredentials: "Email ou mot de passe invalide, vérifiez et réessayez"
            },
            de: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                authTitle: "Anmelden und Registrieren",
                login: "Anmelden",
                register: "Registrieren",
                emailPlaceholder: "E-Mail-Adresse",
                passwordPlaceholder: "Passwort",
                confirmPasswordPlaceholder: "Passwort Bestätigen",
                usernamePlaceholder: "Benutzername",
                welcomeBack: "Willkommen Zurück",
                joinUs: "Treten Sie Uns Bei",
                backToHome: "Zurück zur Startseite",
                loginSuccess: "Anmeldung erfolgreich!",
                registerSuccess: "Registrierung erfolgreich!",
                loginFailed: "Anmeldung fehlgeschlagen, versuchen Sie es erneut",
                registerFailed: "Registrierung fehlgeschlagen",
                passwordMismatch: "Passwörter stimmen nicht überein",
                emailAlreadyRegistered: "E-Mail bereits registriert, melden Sie sich direkt an",
                invalidCredentials: "Ungültige E-Mail oder Passwort, überprüfen und versuchen Sie es erneut"
            },
            ja: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                authTitle: "ログイン・新規登録",
                login: "ログイン",
                register: "新規登録",
                emailPlaceholder: "メールアドレス",
                passwordPlaceholder: "パスワード",
                confirmPasswordPlaceholder: "パスワード確認",
                usernamePlaceholder: "ユーザー名",
                welcomeBack: "おかえりなさい",
                joinUs: "参加する",
                backToHome: "ホームに戻る",
                loginSuccess: "ログイン成功！",
                registerSuccess: "登録成功！",
                loginFailed: "ログインに失敗しました、再試行してください",
                registerFailed: "登録に失敗しました",
                passwordMismatch: "パスワードが一致しません",
                emailAlreadyRegistered: "このメールは既に登録されています、直接ログインしてください",
                invalidCredentials: "メールまたはパスワードが無効です、確認して再試行してください"
            },
            ko: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                authTitle: "로그인 및 회원가입",
                login: "로그인",
                register: "회원가입",
                emailPlaceholder: "이메일 주소",
                passwordPlaceholder: "비밀번호",
                confirmPasswordPlaceholder: "비밀번호 확인",
                usernamePlaceholder: "사용자명",
                welcomeBack: "다시 오신 것을 환영합니다",
                joinUs: "함께하세요",
                backToHome: "홈으로 돌아가기",
                loginSuccess: "로그인 성공!",
                registerSuccess: "회원가입 성공!",
                loginFailed: "로그인에 실패했습니다, 다시 시도해주세요",
                registerFailed: "회원가입에 실패했습니다",
                passwordMismatch: "비밀번호가 일치하지 않습니다",
                emailAlreadyRegistered: "이미 등록된 이메일입니다, 직접 로그인해주세요",
                invalidCredentials: "이메일 또는 비밀번호가 잘못되었습니다, 확인 후 다시 시도해주세요"
            },
            it: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                authTitle: "Accedi e Registrati",
                login: "Accedi",
                register: "Registrati",
                emailPlaceholder: "Indirizzo Email",
                passwordPlaceholder: "Password",
                confirmPasswordPlaceholder: "Conferma Password",
                usernamePlaceholder: "Nome Utente",
                welcomeBack: "Bentornato",
                joinUs: "Unisciti a Noi",
                backToHome: "Torna alla Home",
                loginSuccess: "Accesso riuscito!",
                registerSuccess: "Registrazione riuscita!",
                loginFailed: "Accesso fallito, riprova",
                registerFailed: "Registrazione fallita",
                passwordMismatch: "Le password non corrispondono",
                emailAlreadyRegistered: "Email già registrata, accedi direttamente",
                invalidCredentials: "Email o password non valide, controlla e riprova"
            },
            pt: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                authTitle: "Entrar e Registrar",
                login: "Entrar",
                register: "Registrar",
                emailPlaceholder: "Endereço de Email",
                passwordPlaceholder: "Senha",
                confirmPasswordPlaceholder: "Confirmar Senha",
                usernamePlaceholder: "Nome de Usuário",
                welcomeBack: "Bem-vindo de Volta",
                joinUs: "Junte-se a Nós",
                backToHome: "Voltar ao Início",
                loginSuccess: "Login bem-sucedido!",
                registerSuccess: "Registro bem-sucedido!",
                loginFailed: "Falha no login, tente novamente",
                registerFailed: "Falha no registro",
                passwordMismatch: "As senhas não coincidem",
                emailAlreadyRegistered: "Email já registrado, faça login diretamente",
                invalidCredentials: "Email ou senha inválidos, verifique e tente novamente"
            },
            ru: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                authTitle: "Вход и Регистрация",
                login: "Войти",
                register: "Регистрация",
                emailPlaceholder: "Адрес Email",
                passwordPlaceholder: "Пароль",
                confirmPasswordPlaceholder: "Подтвердить Пароль",
                usernamePlaceholder: "Имя Пользователя",
                welcomeBack: "Добро Пожаловать",
                joinUs: "Присоединяйтесь",
                backToHome: "Вернуться на Главную",
                loginSuccess: "Вход выполнен успешно!",
                registerSuccess: "Регистрация прошла успешно!",
                loginFailed: "Ошибка входа, попробуйте снова",
                registerFailed: "Ошибка регистрации",
                passwordMismatch: "Пароли не совпадают",
                emailAlreadyRegistered: "Email уже зарегистрирован, войдите напрямую",
                invalidCredentials: "Неверный email или пароль, проверьте и попробуйте снова"
            },
            ar: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                authTitle: "تسجيل الدخول والتسجيل",
                login: "تسجيل الدخول",
                register: "التسجيل",
                emailPlaceholder: "عنوان البريد الإلكتروني",
                passwordPlaceholder: "كلمة المرور",
                confirmPasswordPlaceholder: "تأكيد كلمة المرور",
                usernamePlaceholder: "اسم المستخدم",
                welcomeBack: "مرحباً بعودتك",
                joinUs: "انضم إلينا",
                backToHome: "العودة للصفحة الرئيسية",
                loginSuccess: "تم تسجيل الدخول بنجاح!",
                registerSuccess: "تم التسجيل بنجاح!",
                loginFailed: "فشل تسجيل الدخول، يرجى المحاولة مرة أخرى",
                registerFailed: "فشل التسجيل",
                passwordMismatch: "كلمات المرور غير متطابقة",
                emailAlreadyRegistered: "البريد الإلكتروني مسجل بالفعل، يرجى تسجيل الدخول مباشرة",
                invalidCredentials: "البريد الإلكتروني أو كلمة المرور غير صحيحة، يرجى التحقق والمحاولة مرة أخرى"
            },
            hi: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                authTitle: "लॉग इन और रजिस्टर",
                login: "लॉग इन",
                register: "रजिस्टर",
                emailPlaceholder: "ईमेल पता",
                passwordPlaceholder: "पासवर्ड",
                confirmPasswordPlaceholder: "पासवर्ड की पुष्टि करें",
                usernamePlaceholder: "उपयोगकर्ता नाम",
                welcomeBack: "वापस स्वागत है",
                joinUs: "हमसे जुड़ें",
                backToHome: "होम पर वापस जाएं",
                loginSuccess: "लॉग इन सफल!",
                registerSuccess: "रजिस्ट्रेशन सफल!",
                loginFailed: "लॉग इन असफल, कृपया पुनः प्रयास करें",
                registerFailed: "रजिस्ट्रेशन असफल",
                passwordMismatch: "पासवर्ड मेल नहीं खाते",
                emailAlreadyRegistered: "ईमेल पहले से पंजीकृत है, कृपया सीधे लॉग इन करें",
                invalidCredentials: "अमान्य ईमेल या पासवर्ड, कृपया जांच करें और पुनः प्रयास करें"
            },
            tr: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                authTitle: "Giriş ve Kayıt",
                login: "Giriş Yap",
                register: "Kayıt Ol",
                emailPlaceholder: "E-posta Adresi",
                passwordPlaceholder: "Şifre",
                confirmPasswordPlaceholder: "Şifreyi Onayla",
                usernamePlaceholder: "Kullanıcı Adı",
                welcomeBack: "Tekrar Hoş Geldiniz",
                joinUs: "Bize Katılın",
                backToHome: "Ana Sayfaya Dön",
                loginSuccess: "Giriş başarılı!",
                registerSuccess: "Kayıt başarılı!",
                loginFailed: "Giriş başarısız, lütfen tekrar deneyin",
                registerFailed: "Kayıt başarısız",
                passwordMismatch: "Şifreler eşleşmiyor",
                emailAlreadyRegistered: "E-posta zaten kayıtlı, lütfen doğrudan giriş yapın",
                invalidCredentials: "Geçersiz e-posta veya şifre, lütfen kontrol edin ve tekrar deneyin"
            },
            nl: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                authTitle: "Inloggen en Registreren",
                login: "Inloggen",
                register: "Registreren",
                emailPlaceholder: "E-mailadres",
                passwordPlaceholder: "Wachtwoord",
                confirmPasswordPlaceholder: "Wachtwoord Bevestigen",
                usernamePlaceholder: "Gebruikersnaam",
                welcomeBack: "Welkom Terug",
                joinUs: "Doe Mee",
                backToHome: "Terug naar Home",
                loginSuccess: "Inloggen succesvol!",
                registerSuccess: "Registratie succesvol!",
                loginFailed: "Inloggen mislukt, probeer opnieuw",
                registerFailed: "Registratie mislukt",
                passwordMismatch: "Wachtwoorden komen niet overeen",
                emailAlreadyRegistered: "E-mail al geregistreerd, log direct in",
                invalidCredentials: "Ongeldig e-mail of wachtwoord, controleer en probeer opnieuw"
            },
            he: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                authTitle: "התחברות והרשמה",
                login: "התחבר",
                register: "הירשם",
                emailPlaceholder: "כתובת אימייל",
                passwordPlaceholder: "סיסמה",
                confirmPasswordPlaceholder: "אשר סיסמה",
                usernamePlaceholder: "שם משתמש",
                welcomeBack: "ברוך השב",
                joinUs: "הצטרף אלינו",
                backToHome: "חזור לעמוד הבית",
                loginSuccess: "התחברות הצליחה!",
                registerSuccess: "הרשמה הצליחה!",
                loginFailed: "התחברות נכשלה, נסה שוב",
                registerFailed: "הרשמה נכשלה",
                passwordMismatch: "הסיסמאות אינן תואמות",
                emailAlreadyRegistered: "האימייל כבר רשום, התחבר ישירות",
                invalidCredentials: "אימייל או סיסמה לא תקינים, בדוק ונסה שוב"
            },
            bg: {
                appTitle: "spot.gitagent.io",
                appSubtitle: "Discover your next spot!",
                authTitle: "Вход и Регистрация",
                login: "Вход",
                register: "Регистрация",
                emailPlaceholder: "Имейл адрес",
                passwordPlaceholder: "Парола",
                confirmPasswordPlaceholder: "Потвърди парола",
                usernamePlaceholder: "Потребителско име",
                welcomeBack: "Добре дошли отново",
                joinUs: "Присъединете се",
                backToHome: "Обратно към началото",
                loginSuccess: "Входът е успешен!",
                registerSuccess: "Регистрацията е успешна!",
                loginFailed: "Входът неуспешен, опитайте отново",
                registerFailed: "Регистрацията неуспешна",
                passwordMismatch: "Паролите не съвпадат",
                emailAlreadyRegistered: "Имейлът вече е регистриран, влезте директно",
                invalidCredentials: "Невалиден имейл или парола, проверете и опитайте отново"
            }
        };

        // 设置翻译
        window.translations = translations;

        // 当前语言
        let currentLanguage = 'zh';

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializeLanguage();
            setupEventListeners();
            setupLanguageSync();
        });

        function initializeLanguage() {
            // 从父窗口获取当前语言
            currentLanguage = window.parent ? window.parent.currentLanguage || 'zh' : 'zh';
            updateLanguageUI();
        }

        function updateLanguageUI() {
            const t = translations[currentLanguage] || translations['zh'];
            
            document.getElementById('auth-title').textContent = t.authTitle;
            document.getElementById('login-tab').textContent = t.login;
            document.getElementById('register-tab').textContent = t.register;
            document.getElementById('forgot-tab').textContent = t.forgotPassword;
            
            // 更新标签文字
            document.getElementById('login-email-label').textContent = t.emailLabel;
            document.getElementById('login-password-label').textContent = t.passwordLabel;
            document.getElementById('register-username-label').textContent = t.usernameLabel;
            document.getElementById('register-email-label').textContent = t.emailLabel;
            document.getElementById('register-password-label').textContent = t.passwordLabel;
            document.getElementById('register-confirm-password-label').textContent = t.confirmPasswordLabel;
            
            // 更新占位符
            document.getElementById('login-email').placeholder = t.emailPlaceholder;
            document.getElementById('login-password').placeholder = t.passwordPlaceholder;
            document.getElementById('register-username').placeholder = t.usernamePlaceholder;
            document.getElementById('register-email').placeholder = t.emailPlaceholder;
            document.getElementById('register-password').placeholder = t.passwordPlaceholder;
            document.getElementById('register-confirm-password').placeholder = t.confirmPasswordPlaceholder;
            
            // 更新找回密码表单
            document.getElementById('forgot-email-label').textContent = t.forgotEmailLabel;
            document.getElementById('forgot-description').textContent = t.forgotDescription;
            document.getElementById('forgot-text').textContent = t.sendResetLink;
            document.getElementById('back-to-login').textContent = t.backToLogin;
            document.getElementById('forgot-password-link').textContent = t.forgotPasswordLink;
            
            // 更新按钮文字
            document.getElementById('login-text').textContent = t.login;
            document.getElementById('register-text').textContent = t.register;
            document.getElementById('close-modal-link').textContent = t.close;
        }


        function switchTab(tab) {
            // 更新标签页状态
            document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('active'));
            document.getElementById(tab + '-tab').classList.add('active');
            
            // 显示对应表单
            document.querySelectorAll('.auth-form').forEach(form => form.classList.add('hidden'));
            document.getElementById(tab + '-form').classList.remove('hidden');
            
            // 清除消息
            hideMessages();
        }

        function setupEventListeners() {
            // 登录表单
            document.getElementById('login-form').addEventListener('submit', handleLogin);
            
            // 注册表单
            document.getElementById('register-form').addEventListener('submit', handleRegister);
            
            // 验证码表单
            document.getElementById('verification-form').addEventListener('submit', handleVerification);
            
            // 找回密码表单
            document.getElementById('forgot-form').addEventListener('submit', handleForgotPassword);
        }

        async function handleLogin(e) {
            e.preventDefault();
            
            const email = document.getElementById('login-email').value;
            const password = document.getElementById('login-password').value;
            
            showLoading('login');
            hideMessages();
            
            try {
                console.log('🔧 开始登录流程:', email);
                
                // 直接使用后端API登录（更稳定）
                console.log('🔧 使用后端API登录');
                
                // 如果Supabase可用，可以作为备用方案
                // 但目前优先使用后端API以确保稳定性
                
                // 降级到后端API认证
                const apiBaseUrl = window.parent ? window.parent.API_BASE_URL || 'http://localhost:8001' : 'http://localhost:8001';
                console.log('🔧 使用后端API URL:', apiBaseUrl);
                console.log('📤 发送登录请求:', { email });
                
                const response = await fetch(`${apiBaseUrl}/api/auth/login`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ email, password })
                });
                
                console.log('📥 收到响应状态:', response.status);
                const data = await response.json();
                console.log('📥 响应数据:', data);
                
                if (response.ok) {
                    // 保存token
                    localStorage.setItem('access_token', data.access_token);
                    localStorage.setItem('user_id', data.user_id);
                    
                    showSuccess(translations[currentLanguage].loginSuccess);
                    
                    // 通知父窗口登录成功并立即关闭
                    if (window.parent) {
                        window.parent.postMessage({ 
                            action: 'authSuccess',
                            token: data.access_token,
                            user: data.user
                        }, '*');
                        
                        // 延迟关闭模态框
                        setTimeout(() => {
                            window.parent.postMessage({ action: 'closeAuthModal' }, '*');
                        }, 800);
                    }
                } else {
                    console.error('❌ 后端API登录失败:', response.status, data);
                    showError(data.detail || translations[currentLanguage].loginFailed);
                }
            } catch (error) {
                console.error('❌ 登录请求异常:', error);
                showError(translations[currentLanguage].loginFailed);
            } finally {
                hideLoading('login');
            }
        }

        // 全局变量存储注册信息
        let currentRegistrationEmail = '';
        let verificationTimer = null;
        let verificationTimeLeft = 600; // 10分钟

        async function handleRegister(e) {
            e.preventDefault();
            
            const username = document.getElementById('register-username').value;
            const email = document.getElementById('register-email').value;
            const password = document.getElementById('register-password').value;
            const confirmPassword = document.getElementById('register-confirm-password').value;
            
            // 验证密码
            if (password !== confirmPassword) {
                showError(translations[currentLanguage].passwordMismatch);
                return;
            }
            
            showLoading('register');
            hideMessages();
            
            try {
                console.log('📝 开始注册流程:', email);
                
                const apiBaseUrl = window.parent ? window.parent.API_BASE_URL || 'http://localhost:8001' : 'http://localhost:8001';
                console.log('🔧 使用后端API URL:', apiBaseUrl);
                
                const response = await fetch(`${apiBaseUrl}/api/auth/register`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ 
                        username, 
                        email, 
                        password, 
                        confirm_password: confirmPassword 
                    })
                });
                
                const data = await response.json();
                
                if (response.ok) {
                    // 显示注册成功消息
                    showSuccess('验证码已发送到您的邮箱');
                    
                    // 存储注册邮箱
                    currentRegistrationEmail = email;
                    
                    // 延迟显示验证码表单
                    setTimeout(() => {
                        showVerificationForm(email);
                    }, 1000);
                } else {
                    // 根据错误类型显示不同的提示
                    let errorMessage = translations[currentLanguage].registerFailed;
                    
                    if (data.detail) {
                        const errorDetail = data.detail.toLowerCase();
                        
                        // 检查是否是邮箱已经注册（最精确的匹配）
                        if (errorDetail.includes('该邮箱可能已经注册') || 
                            errorDetail.includes('already registered') || 
                            errorDetail.includes('email already') ||
                            errorDetail.includes('该邮箱已注册')) {
                            errorMessage = translations[currentLanguage].databaseError;
                        }
                        // 检查是否是数据库错误（邮箱可能已存在）
                        else if (errorDetail.includes('database error') || 
                                 errorDetail.includes('already exists') || 
                                 errorDetail.includes('duplicate') ||
                                 errorDetail.includes('unique constraint')) {
                            errorMessage = translations[currentLanguage].databaseError;
                        }
                        // 其他错误显示原始错误信息（如果是友好的中文提示）
                        else if (data.detail && !errorDetail.includes('error') && !errorDetail.includes('failed')) {
                            errorMessage = data.detail;
                        }
                        else {
                            errorMessage = translations[currentLanguage].registerFailed;
                        }
                    }
                    
                    showError(errorMessage);
                }
            } catch (error) {
                console.error('❌ 注册请求异常:', error);
                // 网络错误或服务不可用
                if (error.message && error.message.includes('fetch')) {
                    showError(translations[currentLanguage].serviceUnavailable);
                } else {
                    showError(translations[currentLanguage].registerFailed);
                }
            } finally {
                hideLoading('register');
            }
        }

        async function handleForgotPassword(e) {
            e.preventDefault();
            
            const email = document.getElementById('forgot-email').value;
            
            if (!email) {
                showError(translations[currentLanguage].emailRequired || '请输入邮箱地址');
                return;
            }
            
            showLoading('forgot');
            hideMessages();
            
            try {
                console.log('🔧 开始找回密码流程:', email);
                
                // 使用后端API发送重置邮件
                const apiBaseUrl = window.parent ? window.parent.API_BASE_URL || 'https://spot.gitagent.io' : 'https://spot.gitagent.io';
                console.log('🔧 使用后端API URL:', apiBaseUrl);
                
                const response = await fetch(`${apiBaseUrl}/api/auth/forgot-password`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ email })
                });
                
                console.log('📥 收到响应状态:', response.status);
                const data = await response.json();
                console.log('📥 响应数据:', data);
                
                if (response.ok) {
                    console.log('✅ 密码重置邮件发送成功');
                    showSuccess(translations[currentLanguage].resetEmailSent);
                    
                    // 3秒后自动切换回登录页面
                    setTimeout(() => {
                        switchTab('login');
                        hideMessages();
                    }, 3000);
                } else {
                    console.error('❌ 发送重置邮件失败:', response.status, data);
                    
                    // 根据错误类型显示不同的提示
                    let errorMessage = translations[currentLanguage].resetEmailFailed;
                    
                    if (data.detail) {
                        const errorDetail = data.detail.toLowerCase();
                        
                        if (errorDetail.includes('not found') || 
                            errorDetail.includes('not registered') ||
                            errorDetail.includes('未注册')) {
                            errorMessage = translations[currentLanguage].emailNotFound;
                        } else {
                            errorMessage = data.detail;
                        }
                    }
                    
                    showError(errorMessage);
                }
            } catch (error) {
                console.error('❌ 找回密码请求异常:', error);
                showError(translations[currentLanguage].resetEmailFailed);
            } finally {
                hideLoading('forgot');
            }
        }

        function showLoading(formType) {
            document.getElementById(formType + '-button').disabled = true;
            document.getElementById(formType + '-text').classList.add('hidden');
            document.getElementById(formType + '-loading').classList.remove('hidden');
        }

        function hideLoading(formType) {
            document.getElementById(formType + '-button').disabled = false;
            document.getElementById(formType + '-text').classList.remove('hidden');
            document.getElementById(formType + '-loading').classList.add('hidden');
        }

        function showError(message) {
            const errorDiv = document.getElementById('error-message');
            errorDiv.textContent = message;
            errorDiv.classList.remove('hidden');
        }

        function showSuccess(message) {
            const successDiv = document.getElementById('success-message');
            successDiv.textContent = message;
            successDiv.classList.remove('hidden');
        }

        function hideMessages() {
            document.getElementById('error-message').classList.add('hidden');
            document.getElementById('success-message').classList.add('hidden');
        }

        function closeModal() {
            // 通知父窗口关闭模态框
            if (window.parent) {
                window.parent.postMessage({ action: 'closeAuthModal' }, '*');
            }
        }

        // 邮件验证模态框相关函数
        function showEmailVerificationModal(email) {
            const modal = document.getElementById('email-verification-modal');
            const emailDisplay = document.getElementById('verification-email-display');
            const title = document.getElementById('verification-title');
            const message = document.getElementById('verification-message');
            const closeBtn = document.getElementById('verification-close-btn');
            const resendBtn = document.getElementById('verification-resend-btn');
            
            // 更新文本内容
            title.textContent = translations[currentLanguage].registerSuccess;
            message.textContent = translations[currentLanguage].emailVerificationNote;
            closeBtn.textContent = translations[currentLanguage].emailVerificationClose;
            resendBtn.textContent = translations[currentLanguage].resendVerification;
            emailDisplay.textContent = email;
            
            // 显示模态框
            modal.classList.remove('hidden');
            
            // 存储邮箱以便重新发送
            window.currentRegistrationEmail = email;
        }

        function closeVerificationModal() {
            const modal = document.getElementById('email-verification-modal');
            modal.classList.add('hidden');
            
            // 可选：自动切换到登录页面
            setTimeout(() => {
                switchTab('login');
                if (window.currentRegistrationEmail) {
                    document.getElementById('login-email').value = window.currentRegistrationEmail;
                }
            }, 500);
        }
        
        function closeVerificationModalOnBackdrop(event) {
            // 只有点击背景时才关闭（不是点击内容区域）
            if (event.target === event.currentTarget) {
                closeVerificationModal();
            }
        }

        function resendVerificationEmail() {
            if (!window.currentRegistrationEmail) {
                showError(translations[currentLanguage].registerFailed);
                return;
            }
            
            // 这里可以添加重新发送验证邮件的逻辑
            // 暂时显示一个提示消息
            showSuccess('验证邮件已重新发送到 ' + window.currentRegistrationEmail);
            
            // 可以调用后端API重新发送邮件
            // resendVerificationEmailAPI(window.currentRegistrationEmail);
        }
        
        function goBack() {
            window.location.href = '/';
        }

        function setupLanguageSync() {
            // 监听父窗口的语言变化
            if (window.parent) {
                // 立即同步一次
                syncWithParentLanguage();
                
                // 定期检查父窗口的语言是否发生变化
                setInterval(() => {
                    syncWithParentLanguage();
                }, 500);
                
                // 监听父窗口的语言变化事件
                window.parent.addEventListener('languageChanged', (event) => {
                    if (event.detail && event.detail.language) {
                        currentLanguage = event.detail.language;
                        updateLanguageUI();
                    }
                });
            }
        }
        
        function syncWithParentLanguage() {
            const parentLanguage = window.parent ? window.parent.currentLanguage : null;
            if (parentLanguage && parentLanguage !== currentLanguage) {
                console.log('认证页面语言同步:', currentLanguage, '->', parentLanguage);
                currentLanguage = parentLanguage;
                updateLanguageUI();
            }
        }

        // 显示验证码表单
        function showVerificationForm(email) {
            // 隐藏所有表单
            document.querySelectorAll('.auth-form').forEach(form => form.classList.add('hidden'));
            
            // 显示验证码表单
            document.getElementById('verification-form').classList.remove('hidden');
            
            // 更新邮箱显示
            document.getElementById('verification-email-display').textContent = email;
            
            // 清空验证码输入框
            document.getElementById('verification-code').value = '';
            
            // 开始倒计时
            startVerificationTimer();
            
            // 聚焦到验证码输入框
            setTimeout(() => {
                document.getElementById('verification-code').focus();
            }, 100);
        }

        // 处理验证码提交
        async function handleVerification(e) {
            e.preventDefault();
            
            const email = currentRegistrationEmail;
            const verificationCode = document.getElementById('verification-code').value;
            
            if (!verificationCode || verificationCode.length !== 6) {
                showError('请输入6位数字验证码');
                return;
            }
            
            showLoading('verification');
            hideMessages();
            
            try {
                const apiBaseUrl = window.parent ? window.parent.API_BASE_URL || 'http://localhost:8001' : 'http://localhost:8001';
                
                const response = await fetch(`${apiBaseUrl}/api/auth/verify-email`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ 
                        email, 
                        verification_code: verificationCode 
                    })
                });
                
                const data = await response.json();
                
                if (response.ok) {
                    showSuccess('注册成功！正在为您登录...');
                    
                    // 停止倒计时
                    if (verificationTimer) {
                        clearInterval(verificationTimer);
                        verificationTimer = null;
                    }
                    
                    // 注册成功后直接关闭模态框，不跳转到登录页
                    setTimeout(() => {
                        // 通知父窗口注册成功
                        if (window.parent) {
                            window.parent.postMessage({ 
                                action: 'registrationSuccess',
                                email: email,
                                message: '注册成功！欢迎使用OrientDirector'
                            }, '*');
                            
                            // 关闭认证模态框
                            window.parent.postMessage({ action: 'closeAuthModal' }, '*');
                        }
                        currentRegistrationEmail = '';
                    }, 1500);
                } else {
                    showError(data.detail || '验证码错误，请重新输入');
                }
            } catch (error) {
                console.error('❌ 验证码验证异常:', error);
                showError('网络错误，请重试');
            } finally {
                hideLoading('verification');
            }
        }

        // 重新发送验证码
        async function resendVerificationCode() {
            if (!currentRegistrationEmail) {
                showError('请重新注册');
                return;
            }
            
            const resendButton = document.getElementById('resend-code-button');
            resendButton.disabled = true;
            resendButton.querySelector('#resend-text').textContent = '发送中...';
            
            try {
                const apiBaseUrl = window.parent ? window.parent.API_BASE_URL || 'http://localhost:8001' : 'http://localhost:8001';
                
                const response = await fetch(`${apiBaseUrl}/api/auth/send-verification-code`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ 
                        email: currentRegistrationEmail 
                    })
                });
                
                const data = await response.json();
                
                if (response.ok) {
                    showSuccess('验证码已重新发送');
                    
                    // 重置倒计时
                    verificationTimeLeft = 600;
                    startVerificationTimer();
                    
                    // 30秒后才能再次发送
                    setTimeout(() => {
                        resendButton.disabled = false;
                        resendButton.querySelector('#resend-text').textContent = '重新发送验证码';
                    }, 30000);
                } else {
                    showError(data.detail || '发送失败，请重试');
                    resendButton.disabled = false;
                    resendButton.querySelector('#resend-text').textContent = '重新发送验证码';
                }
            } catch (error) {
                console.error('❌ 重新发送验证码异常:', error);
                showError('网络错误，请重试');
                resendButton.disabled = false;
                resendButton.querySelector('#resend-text').textContent = '重新发送验证码';
            }
        }

        // 返回注册表单
        function backToRegister() {
            // 停止倒计时
            if (verificationTimer) {
                clearInterval(verificationTimer);
                verificationTimer = null;
            }
            
            // 清空当前注册邮箱
            currentRegistrationEmail = '';
            
            // 切换到注册表单
            switchTab('register');
        }

        // 开始验证码倒计时
        function startVerificationTimer() {
            // 清除现有计时器
            if (verificationTimer) {
                clearInterval(verificationTimer);
            }
            
            verificationTimeLeft = 600; // 10分钟
            
            verificationTimer = setInterval(() => {
                verificationTimeLeft--;
                
                const minutes = Math.floor(verificationTimeLeft / 60);
                const seconds = verificationTimeLeft % 60;
                const timeDisplay = `${minutes}:${seconds.toString().padStart(2, '0')}`;
                
                const timerElement = document.getElementById('timer-countdown');
                if (timerElement) {
                    timerElement.textContent = timeDisplay;
                }
                
                if (verificationTimeLeft <= 0) {
                    clearInterval(verificationTimer);
                    verificationTimer = null;
                    showError('验证码已过期，请重新注册');
                    setTimeout(() => {
                        backToRegister();
                    }, 2000);
                }
            }, 1000);
        }

    </script>
</body>
</html>
